package logic

import (
	cache "73/models/cache"
	"73/models/mysql"
	"73/pkg"
	"context"
	"fmt"

	"73/userrpc/internal/svc"
	"73/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterLogic) Register(in *userrpc.RegisterRequest) (*userrpc.RegisterResponse, error) {
	// todo: add your logic here and delete this line
	var user mysql.User
	mysql.DB.Debug().Where("mobile = ?", in.Mobile).Find(&user)
	if user.ID != 0 {
		return nil, fmt.Errorf("账户已存在")
	}
	s, _ := cache.Rdb.Get(cache.Ctx, "captcha"+in.Mobile).Result()
	if s != in.CaptchaCode {
		return nil, fmt.Errorf("图形验证码错误")
	}
	result, _ := cache.Rdb.Get(cache.Ctx, "send"+in.Mobile).Result()
	if result != in.SmsCode {
		return nil, fmt.Errorf("短信验证码错误")
	}
	user.Mobile = in.Mobile
	user.Password = pkg.Md5(in.Password)
	mysql.DB.Debug().Create(&user)
	return &userrpc.RegisterResponse{
		Id: int64(user.ID),
	}, nil
}
